package com.example.apidocserver.infrastructure.config.filter;


import com.example.apidocserver.infrastructure.util.user.CurrentUser;
import com.example.apidocserver.infrastructure.config.security.UserDetailsImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 生成接口文档连接器
 *
 * @author xyqlg
 */
@Component
@Slf4j
public class ApiDocFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        String requestURI = req.getRequestURI();
        setCurrentUser();
        log.info("requestURI = " + requestURI);
        if ("/this/getParam/test".equals(requestURI)) {
            req.getRequestDispatcher("/this/getParam").forward(servletRequest, servletResponse);
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    private void setCurrentUser() {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            Object principal = authentication.getPrincipal();
            if (!(principal instanceof UserDetailsImpl)) {
                return;
            }
            CurrentUser.setUser((UserDetailsImpl) principal);
        } catch (Exception e) {
            log.error("setCurrentUser: {}", e.getCause());
        }
    }


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
